package com.ask.jwtdemo;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;

public class JwtExample {
    private static final String SECRET_KEY = generateBase64UrlSafeKey();

    private static String generateBase64UrlSafeKey() {
        byte[] keyBytes = new byte[32]; // 256 bits
        new SecureRandom().nextBytes(keyBytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
    }

    public static String generateToken() {
        Key key = new SecretKeySpec(Base64.getUrlDecoder().decode(SECRET_KEY), SignatureAlgorithm.HS256.getJcaName());

        String jwt = Jwts.builder()
                .setSubject("1234567890")
                .claim("name", "John Doe")
                .claim("admin", true)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000))
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();

        return jwt;
    }

    public static void main(String[] args) {
        String token = generateToken();
        System.out.println("Generated JWT: " + token);
    }
}
